﻿const fse = require("fs-extra");
const moment = require("moment");
const uuid = require("uuid");
const path = require("path");
const Jimp = require("jimp");
const router = require("koa-router")();
const prettyBytes = require("pretty-file-bytes");

/**
 * api {get} /home/app/file/page 文件列表
 *
 * apiParam {Number} baas_id 应用id
 *
 */
router.get("/page/:page", async (ctx, next) => {
  const page = ctx.params.page > 0 ? parseInt(ctx.params.page) : 1;
  const user = ctx.user;
  const baas = ctx.baas;
  if (!user.id) {
    ctx.error("参数错误");
    return;
  }
  // 查询用户应用下的文件
  const fileList = await BaaS.Models.file
    .query(qb => {
      qb.where("baas_id", "=", baas.id);
      qb.orderBy("id", "desc");
    })
    .fetchPage({
      pageSize: ctx.config.pageSize,
      page: page,
      withRelated: []
    });

  // 给文件路径加上完整路径
  for (const key in fileList.data) {
    if (ctx.config("qiniu")) {
      fileList.data[key].savepath = 
        ctx.config("qiniu.host")+
        fileList.data[key].savename
      ;
    }
  }
  if (fileList.data.length) {
    ctx.success(fileList);
  } else {
    ctx.error("没有相关文件");
  }
});
/**
 *
 * @api {post} /home/app/file/upload 上传文件
 *
 * @apiSuccess {File} file 上传的文件
 *
 * @apiSampleRequest /home/app/file/upload
 *
 */
router.post("/uploads", async (ctx, next) => {
  const user = ctx.user;
  const baas = ctx.baas;
  if (!ctx.file && !ctx.file.file) {
    throw new Error("Upload Image Error");
  }
  const file = ctx.file.file;
  const key = `lock:image:upload:url:${ctx.url}:name:${file.name}:type:${
    file.type
  }:size:${file.size}`;
  // 文件大小单位转成kb
  const fileSize = parseFloat(prettyBytes(file.size, "mb"));
  if (fileSize > ctx.config("maxFile")) {
    ctx.error("文件过大");
    return;
  }
  const locked = await BaaS.redis.lock(key);
  if (locked) {
    // 后缀名
    let ext = "";
    switch (file.type) {
      case "image/gif":
        ext = "gif";
        break;
      case "image/jpg":
        ext = "jpg";
        break;
      case "image/pjpeg":
        ext = "jpg";
        break;
      case "image/jpeg":
        ext = "jpg";
        break;
      case "image/png":
        ext = "png";
        break;
      case "image/x-png":
        ext = "png";
        break;
      case "application/json":
        ext = "json";
        break;
      case "application/zip":
        ext = "zip";
        break;
      case "application/x-zip-compressed":
        ext = "zip";
        break;
      case "iapplication/javascript":
        ext = "js";
        break;
      case "application/x-sql":
        ext = "sql";
        break;
      default:
        ext = path.parse(file.name).ext.substring(1);
        break;
    }
    const savepath = moment().format("YYYY-MM-DD");
    const savename = uuid() + "." + ext;
    // 存数据库
    const avater = await BaaS.Models.file
      .forge({
        baas_id: baas.id,
        name: file.name,
        ext: ext,
        type: file.type,
        size: file.size,
        savename: savename,
        savepath: savepath
      })
      .save();
    // 上传七牛
    if (ctx.config("qiniu")) {
      const imageUrl = await ctx.uploadFile(file.path, savename);
      ctx.success(`${imageUrl}`, "success");
    } else {
      // 上传本地
      await fse.move(
        file.path,
        path.resolve("www", "uploads", savepath, savename)
      );
      if (ext == "png" || ext == "jpg" || ext == "gif") {
        // 图片压缩 质量 30
        Jimp.read(path.resolve("www/uploads/", savepath, savename))
          .then(lenna => {
            lenna
              .quality(30)
              .write(path.resolve("www/uploads/", savepath, savename));
          })
          .catch(err => {
            console.error(err);
          });
      }
      ctx.success(
        {
          url: `https://${ctx.host}/uploads/${savepath}/${savename}`,
          avater_id: avater.id
        },
        "success"
      );
    }
    await BaaS.redis.unlock(key);
  } else {
    console.log(`${key} Waiting`);
    ctx.error(`${key} Waiting`);
  }
});
/**
 *
 * @api {post} /home/app/file/delete 删除图片
 *
 * @apiSuccess {Number} del_id 要删除的id
 *
 * @apiSampleRequest /home/app/file/delete
 *
 */
router.post("/delete", async (ctx, next) => {
  const user = ctx.user;
  const baas = ctx.baas;
  const delId = ctx.post.del_id;
  if (parseInt(delId) < 1) {
    ctx.error("参数有误");
    return;
  }
  const result = await BaaS.Models.file.forge({ id: delId }).destroy();
  ctx.success(result);
});
/**
 *
 * @api {post} /home/app/file/rename 修改名称
 *
 * @apiSuccess {Number} id 要修改的id
 * @apiSuccess {Number} newName 要修改的新名称
 *
 * @apiSampleRequest /home/app/file/rename
 *
 */
router.post("/rename", async (ctx, next) => {
  const user = ctx.user;
  const baas = ctx.baas;
  const { id, newName } = ctx.post;
  if (parseInt(id) < 1 || !newName) {
    ctx.error("参数有误");
    return;
  }
  const result = await BaaS.Models.file.forge({ id: id, name: newName }).save();

  ctx.success(result);
});

module.exports = router;
